
// 有 Sea.js 等 CMD 模块加载器存在
define(function(require,exports,module){
	(function() {
		// Private array of chars to use
		var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

		Math.uuid = function (len, radix) {
			var chars = CHARS, uuid = [], i;
			radix = radix || chars.length;

			if (len) {
				// Compact form
				for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
			} else {
				// rfc4122, version 4 form
				var r;

				// rfc4122 requires these characters
				uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
				uuid[14] = '4';

				// Fill in random data.  At i==19 set the high bits of clock sequence as
				// per rfc4122, sec. 4.1.5
				for (i = 0; i < 36; i++) {
					if (!uuid[i]) {
						r = 0 | Math.random()*16;
						uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
					}
				}
			}

			return uuid.join('');
		};

		// A more performant, but slightly bulkier, RFC4122v4 solution.  We boost performance
		// by minimizing calls to random()
		Math.uuidFast = function() {
			var chars = CHARS, uuid = new Array(36), rnd=0, r;
			for (var i = 0; i < 36; i++) {
				if (i==8 || i==13 ||  i==18 || i==23) {
					uuid[i] = '-';
				} else if (i==14) {
					uuid[i] = '4';
				} else {
					if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
					r = rnd & 0xf;
					rnd = rnd >> 4;
					uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
				}
			}
			return uuid.join('');
		};

		// A more compact, but less performant, RFC4122v4 solution:
		Math.uuidCompact = function() {
			return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
				var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
				return v.toString(16);
			});
		};
	})();


	var $ = require("zepto");
	var wx = require('./wx');


	//var base = 'http://office.huo.so:9999/hitgou';
	var base = 'http://api.haitai.huo.so/hitgou';

	function g(){
		this.init.call(this);
	}
	g.prototype = {
		init : function(){
			this.initLoading();
			this.initTip();
			this.initFixNav();
			////this.setCookie('X-APIHitgou-AccessToken','a50cc6f46887510bce6bb212dd637af1');
            //
			//if(typeof this.getCookie('X-APIHitgou-ClientId') == 'undefined'){
            //
			//	this.setCookie('X-APIHitgou-ClientId','02'+Math.uuid(32));
			//}
			//this.wxFun(); //默认为每个页面注册微信事件
			var _this = this;
			//$('#clearCookie').click(function(){
			//	_this.delCookie('X-APIHitgou-ClientId');
			//	var keys=document.cookie.match(/[^ =;]+(?=\=)/g);
			//	if (keys) {
			//		for (var i = keys.length; i--;)
			//			document.cookie=keys[i]+'=0;expires=' + new Date( 0).toUTCString() +";path=/;domain=.huo.so"
			//	}
			//});

		},
		initFixNav : function(){
			var arr = window.location.pathname.split("/");
			var currentPage = arr[2];
			if(currentPage == "my" || currentPage == "had" || currentPage == "want" || currentPage == "publish" || currentPage == "focus" || currentPage == "fans" || currentPage == "agree" || currentPage == "provide"|| currentPage == "message"){
				$('.me').addClass('me_on');
			}else if(currentPage == ""){
				$('.find').addClass('find_on');
			}
		},
		initLoading : function(){
			$('body').append('<div id="tip" class="p_tip dn"><span></span></div>');
		},
		initTip : function(){
			$('body').append('<div class="spinner dn"  id="loading">'+
			'<div class="double-bounce1"></div>'+
			'<div class="double-bounce2"></div>'+
			'</div>');
		},
		loading : function(){
			$("#loading").show();
			return this;
		},
		loadingHide : function(){
			$("#loading").hide();
			return this;
		},
		tip : function(txt,time,callback){
			var time = time || 2000;
			var _tip = $("#tip");
			$("#tip span").text(txt);
			_tip.show();
			setTimeout(function(){
				_tip.hide();
				if(typeof callback == 'function'){callback.call()}
			},time);
			return this;
		},
		getUrlValue :  function(name)//获取URL参数
		{
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
			if(window.location.search.substr(1).match(reg))
			{
				arr=window.location.search.substr(1).match(reg);
				return decodeURIComponent(arr[2]);
			}
		},
		ajax : function(obj){
			var _this = this;
			//	clientId = this.getCookie('X-APIHitgou-ClientId'),
			//	location = window.encodeURIComponent(window.location.href);
			////alert('X-APIHitgou-AccessToken:'+this.getCookie('X-APIHitgou-AccessToken')+'X-APIHitgou-ClientId:'+this.getCookie('X-APIHitgou-ClientId'));
			////通过是否存在cookie来判断用户是否生成
			//if(typeof this.getCookie('X-APIHitgou-AccessToken') == 'undefined'){
			//	window.location.href = 'http://dev02.huo.so/hitgou-user/signin/auth/wechat?scope=snsapi_userinfo&appid=kstore&clientId='+clientId+'&redirectUrl='+location;//去微信授权
			//	return false;
			//}
			var errorMsg = obj.errorMsg || '数据请求失败，请重试';
			$.ajax({
				url : base + obj.url,
				type : 'GET',
				data : obj.data,
				dataType : 'jsonp',
				success : function(json){
					if(json.status == 2000){
						obj.success.call(this,json);
					}else{
						_this.loadingHide().tip(errorMsg);
						return false;
					}
				},
				error : obj.error || function(){
					_this.loadingHide().tip(errorMsg);
					return false;
				}
			})
		},
		ajax_common : function(obj){ //公用普通AJAX请求，不需要授权调用的AJAX走这里
			var _this = this;
			this.loading();
			$.ajax({
				url : base + obj.url,
				type : obj.type || 'GET',
				data : obj.data,
				dataType : 'jsonp',
				success : function(json){
					if(json.status == 2000){
						obj.success.call(this,json);
					}else if(json.status == 1002){ //授权过期了,重新授权登录
						_this.wxAuth();
						return false;
					}else{
						if(obj.error){
							obj.error();
							return;
						}
						_this.loadingHide().tip(errorMsg);
						return false;
					}
				},
				error : obj.error || function(){
					_this.loadingHide().tip(errorMsg);
					return false;
				}
			})
		},
		setCookie : function(name,value){//写cookies
			var Days = 1000;
			var exp = new Date();
			exp.setTime(exp.getTime() + Days*24*60*60*1000);
			document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/;domain=.huo.so";
			//document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/";
		},
		getCookie : function(name){
			var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
			if(arr=document.cookie.match(reg))
				return unescape(arr[2]);
			else
				return undefined;
		},
		delCookie : function(name)
		{
			var exp = new Date();
			exp.setTime(exp.getTime() - 1);
			var cval=this.getCookie(name);
			if(cval!=null)document.cookie= name + "="+cval+";expires="+exp.toGMTString()+";path=/";
		},
		time_format:function(value) {
			//var value = new Date(value.replace(/-/g,"/"));
			var value = new Date(value);
			var TIME_MIN = 60 * 1000;
			var TIME_HOUR = 60 * 60 * 1000;
			var TIME_DAY = 24 * 60 * 60 * 1000;
			var now=new Date();
			var diff=parseInt(now.getTime()-value.getTime());  //时间差的毫秒数
			if (diff < TIME_MIN) {
				return "刚刚";
			} else if (diff >= TIME_MIN && diff < TIME_HOUR) {
				return parseInt(diff / TIME_MIN) + "分钟前";
			} else if (diff >= TIME_HOUR && diff < TIME_DAY) {
				return parseInt(diff / TIME_HOUR) + "小时前";
			} else if (diff >= TIME_DAY && diff < TIME_DAY * 3) {//3天
				return parseInt(diff / TIME_DAY) + "天前";
			} else {
				return value.Format("yyyy-MM-dd");
			}
		},
		toDownload : function(){ //去下载页面
			window.location.href = 'http://office.huo.so:9999/h5/mrht/index.html';
		},
		imgUrlFormat : function(url,mod,w,h){ //图片URL格式化，主要是处理七牛图片，添加参数
			if(typeof url == 'undefined'){
				return false;
			}
			if(/qiniucdn/.test(url)){ //七牛添加参数
				var mod = mod || 2,
					w = w || 640,   //图片不传宽度，默认为640px,
					h = h ? '/h/'+h : ''; //不传宽度，默认就自动高
				return url += '?imageView2/' + mod + '/w/' + w + h;
			}else{
				return url; //不处理，直接返回
			}
		},
		shareTipHide : function(){
			$('.share-tip').hide();
			$('.pop-bg').hide();
		},
		wxFun : function(obj){ //注册微信事件
			//if(typeof obj == 'undefined'){
			//	obj = {};//定义空对象，防止obj.title报错
			//}
			//wx.wxAPI({
			//	jsapi_ticket : jsapi_ticket,//必须
			//	appid : appid,//必须
			//	share : true,//是否需要分享默认false
			//	title : obj.title || shareObj.title,//share:true，分享标题
			//	desc : obj.desc || shareObj.desc,//share:true，分享描述
			//	url : obj.url || shareObj.url,//share:true，分享链接
			//	imgUrl : obj.imgUrl || shareObj.imgUrl,//share:true，分享图片
			//	ready : obj.ready || function(weixin){
			//		weixin.showAllNonBaseMenuItem(); //显示所有功能按钮接口
			//	},
			//	shareCallBack : obj.shareCallBack || '',//分享后回调函数，可选
			//	shareCancle : obj.shareCancle || ''//取消分享后回调函数，可选
			//});
		}
	};
	Date.prototype.Format = function (fmt) {
		var o = {
			"M+": this.getMonth() + 1, //月份
			"d+": this.getDate(), //日
			"h+": this.getHours(), //小时
			"m+": this.getMinutes(), //分
			"s+": this.getSeconds(), //秒
			"q+": Math.floor((this.getMonth() + 3) / 3), //季度
			"S": this.getMilliseconds() //毫秒
		};
		if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (var k in o)
			if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		return fmt;
	}
	module.exports = new g();
})
//}